
<template>
	<view>
		<!-- 404页面 -->
		<view class="noData" v-if="netWorkType == 'none'">
			<noData @handle="refresh"></noData>
		</view>
		<view v-if="netWorkType != 'none'">
			<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
			<view :style="{marginTop:screenHeight+'px'}" class="container tui-skeleton">
				<view class="cpt-mask" v-if="showMaskloading">
					<view class="mask-tip">
						<image src="https://xoimg.aiouning.com/static/cash_loading.gif" style="width:120rpx;height: 120rpx;"></image>
						<view class="txt">支付中...</view>
					</view>
				</view>
				<!-- <view class="top-header-box">
					<view @click="backFun" class="iconfont back">&#xe61b;</view>
					<view class="header-title">确认订单</view>
				</view> -->
				<view class="bg-body">
					
				</view>
				<view class="content-wrap">
					<view style="display: flex;" class="deliver_type">
						<view style='text-align: center; width: 50%;line-height: 80rpx;' :class="deliver_type == 0?'deliver':''" @tap="changeDeliverType(0)">收货地址</view>
						<view style='text-align: center; width: 50%;line-height: 80rpx;' :class="deliver_type == 1?'deliver':''"   @tap="changeDeliverType(1)">门店自提</view>
					</view>
					<!-- 地址 -->
					<view class="address-box"  @tap="selectAddress" v-if="deliver_type == 0">
						<view class="iconfont location">&#xe627;</view>
						<view class="name-phone-address" v-if="data.address.name!=undefined" >
							<view class="item" style="padding-bottom:10rpx;">{{data.address.name}} {{data.address.tel}} </view>
							<view class="item">{{data.address.province_name}} {{data.address.city_name}} {{data.address.area_name}} {{data.address.detail}}</view>
						</view>
						<view class="name-phone-address" v-if="data.address.name==undefined"  >
							<view class="item">请选择地址 </view>
						</view>
						<view class="right-icon iconfont">&#xe626;</view>
					</view>
					<!-- 门店 -->
					<view class="address-box"  @tap="selectAddress"   v-if="deliver_type == 1">
						<view class="iconfont location">&#xe627;</view>
						<view class="name-phone-address" v-if="data.deliverStoreObj.store_name!=undefined" >
							<view class="item" style="padding-bottom:10rpx;display: flex;"><text class="deliver-store">{{data.deliverStoreObj.store_name}}</text> <text style="width: 210rpx;">{{data.deliverStoreObj.tel}}</text>  </view>
							<view class="item" v-if="data.deliverStoreObj.province_name!=undefined">{{data.deliverStoreObj.province_name}} {{data.deliverStoreObj.city_name}} {{data.deliverStoreObj.area_name}} {{data.deliverStoreObj.address}}</view>
						</view>
						<view class="name-phone-address" v-if="data.deliverStoreObj.store_name==undefined"  >
							<view class="item">请选择门店</view><!-- 请选择门店 -->
						</view>
						<view class="right-icon iconfont">&#xe626;</view>
					</view>
					<!-- 商品 -->
					<view class="goods-box" v-for="item in data.list">
						<view class="goods-img">
							<image :src="item.cover_image" mode="widthFix"></image>
						</view>
						<view class="goods-describe">
							<view class="main-title">{{item.name}}</view>
							<view class="small-text">{{item.norms_value_name}}</view>
							<view class="small-text">库存：{{item.number}}</view>
							<view class="goods-price">
								<view class="small-price"><text>￥</text>{{ parseFloat(item.price).toFixed(2) }}</view>
								<view class="small-text">数量:{{item.num}}</view>
							</view>
							<!-- <view class="small-price"><text>￥</text>{{parseFloat(item.price).toFixed(2)}}</view>
							<view class="small-text">数量:{{item.num}}</view> -->
						</view>
						<view class="line"></view>
					</view>
					<!-- <view class="row-cell-box">
						<view>套餐</view>
						<view>{{data.list.package_day}}天 | ￥{{data.list.package_price}}</view>
					</view> -->
					
					<view class="row-box">
						<view class="row-cell-box" >
							<view>商品金额</view>
							<view>￥{{parseFloat(amount).toFixed(2)}}</view>
						</view> 
						<view class="row-cell-box" v-if="deliver_type ==0 && related_type=='bargain'">
							<view>运费</view>
							<view>￥{{deliveFee.bargain}}</view><!-- {{data.list.delivers[0]}} -->
						</view>
						<view class="row-cell-box" v-if="deliver_type ==0 && related_type=='product'  ">
							<view>运费</view>
							<view v-if="noDeliveFee>amount">￥{{deliveFee.product}}</view><!-- {{data.list.delivers[0]}} -->
							<view v-else> 免运费</view>
						</view>
						<view class="row-cell-box" v-if="deliver_type ==0 && related_type=='batch'  ">
							<view>运费</view>
							<view v-if="noDeliveFee>amount">￥{{deliveFee.batch}}</view><!-- {{data.list.delivers[0]}} -->
							<view v-else> 免运费</view>
						</view>
						<view class="row-cell-box" >
							<view>包装费</view>
							<view>￥0 </view>
						</view> 
						<view class="row-cell-box" @tap.stop="showChangeInvoice" style="padding-bottom: 20rpx;border-radius:0 0 16rpx 16rpx;">
							<view>发票</view>
							<view class="gray">{{fp_type_name}} <text class="iconfont">&#xe644;</text></view>
						</view>
						<view class="row-cell-box" >
							<view>优惠券</view>
							<view class="righr-part" @tap="useCoupon()" > 
								<view class="i-item manjian-bg">
									<!-- <image :src="OSS_HOST+'img/manjian.png'" mode="widthFix"></image> -->
									<text class="manjian-txt">满减券</text>
								</view>
								<view class="i-item" v-if="selectCoupon.coupon_money>0">-￥{{selectCoupon.coupon_money}}</view>
								<view class="iconfont">
									&#xe620;
								</view>
							</view>
						</view>
						<view class="row-cell-box" >
							<view></view>
							<view class="count-price">小计：
								<text v-if="related_type=='bargain'">￥{{deliver_type==0 && related_type=='bargain'? parseFloat(amount+deliveFee.bargain-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}</text>
								
								<text  v-else-if="related_type=='batch'">
									<!-- && noDeliveFee>batch_amount -->
									{{deliver_type==0&& noDeliveFee>amount   ? parseFloat(amount+deliveFee.batch-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}
									
									<!-- {{ ( parseInt(data.list.amount[deliver_type])- parseInt(selectCoupon.coupon_money)-parseInt(data.list.cash)).toFixed(2)}}
									authFreeCash -->
								</text>
								<text  v-else>
									{{deliver_type==0  && noDeliveFee>amount ? parseFloat(amount+deliveFee.product-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}
									
									<!-- {{ ( parseInt(data.list.amount[deliver_type])- parseInt(selectCoupon.coupon_money)-parseInt(data.list.cash)).toFixed(2)}}
									authFreeCash -->
								</text>
							</view>
						</view>
					</view>
					<view class="pay-box" style="margin-bottom: 20px;" v-if="related_type == 'batch'">
						<view class="title" >支付方式：</view>
						
							<view class="type-box flex-box" @tap="changePayType(item,index)" v-for="(item, index) in radioItems" :key="item.value">
								<view class="desc">
									<text class="iconfont checked" v-if="index==current">&#xe61e; </text>
									<text class="iconfont" v-else>&#xe638; </text>
									<!-- {{item.name}} -->
								</view>
								<view class="price" >
									<!-- <text class="iconfont" v-if="index==current">&#xe61e; </text>
									<text class="iconfont" v-else>&#xe638; </text> -->
									{{item.name}}
									
								</view>
							
							</view>
						
					</view>
					
					<!-- <view class="row-cell-box" v-if="deliver_type ==1">
						<view>自提费</view>
						<view>{{data.list.delivers[1]}}</view>
					</view> -->
					<!-- <view class="row-cell-box" v-if="deliver_type == 0">
						<view>优惠</view>
						<view class="righr-part" @tap="useCoupon()">
							<view class="i-item manjian-bg">
								<image :src="OSS_HOST+'img/manjian.png'" mode="widthFix"></image>
								<text class="manjian-txt">满减券</text>
							</view>
							<view class="i-item" v-if="selectCoupon.coupon_money>0">-￥{{selectCoupon.coupon_money}}</view>
							<view class="iconfont">
								&#xe62b;
							</view>
						</view>
					</view> -->
					<!-- <view class="row-cell-box" style="padding-bottom: 20rpx;border-radius:0 0 16rpx 16rpx;">
						<view>配送</view>
						<view class="gray">京东物流</view>
					</view> -->
					<!-- 押金 -->
					<!-- <view class="row-cell-box set-margintop">
						<view>押金</view>
						<view class="gray">￥{{data.list.cash}}
						</view>
					</view> -->
					<!--状态true时根据 cash_code显示已免押或者已支付-->
					<!-- <view class="produce-cash-box" v-if="data.usable_cash.status && data.usable_cash.cash_code=='onlinePay'">
						<view class="p-title">商品押金</view>
						<view class="tag">已支付</view>
					</view>

					<view class="produce-cash-box" v-if="data.usable_cash.status && data.usable_cash.cash_code=='wechatFreePay'">
						<view class="p-title">商品押金</view>
						<view class="tag free">已免押</view>
					</view> -->
<!-- 
					<view v-if="!data.usable_cash.status" class="row-cell-wrap top-left-right-radio" style="margin-top: 30rpx;padding-top: 20rpx;padding-bottom: 20rpx;">
						<view>商品押金</view>
						<view class="righr-part">￥{{data.list.cash}}</view>
					</view>
					<view  class="row-cell-box top-left-right-radio" >
						
							<text class="green-border-box" style=" padding: 10rpx; border: 2rpx solid #07C160; color: #07C160;border-radius: 32rpx;">
								微信支付分&nbsp|&nbsp600分及以上优享
							</text>
						
					</view> -->
					<!-- 状态false未支付 -->
					<!-- <view class="row-cell-wrap radio-box" v-if="!data.usable_cash.status">
						<radio-group @change="cashRadioChange" >
							<label  style="margin-top: 10rpx;" v-for="(item, index) in radioItems" :key="item.value">
								<view>
									<radio :value="item.value" :checked="index === current" style="transform: scale(0.7);" color='#69A4FE' />
								</view>
								<view>{{item.name}}</view>
								
							</label>
						</radio-group>
					</view> -->
					<!-- <view class="fp-box">
						<view class="fpchange">
							发票： <switch v-model="is_fp" checked="fpcheck" @change="fpChange"/>
						</view>
					</view> -->
					<view class="tip-box" v-if="deliver_type == 1">
						<view class="tip-txt">
							<view class="txt">联系人：</view>
							<view class="input-box"><input type="text" v-model="pick_user_name" placeholder="请输入自提联系人" ></view>
						</view>
						<view class="tip-txt">
							<view class="txt">联系电话：</view>
							<view class="input-box"><input type="text" name="" v-model="pick_user_tel" placeholder="请输入自提联系电话" ></view>
						</view>
					</view>
					<view class="tip-box" v-if="selectedPayType =='pubpay'">
						<view class="">
							生成订单后请在3日内向指定的对公账号打款{{deliver_type==0&& noDeliveFee>amount ? parseFloat(amount+deliveFee.batch-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}元，并前往该订单上传转账凭证和账单上的流水号或凭证号等，<span style="color: red;">如果无法上传图片，联系客服帮您处理图片上传，</span>超时将取消该订单.
							
						</view>
						<view class="">
							<view class="txt">上传对公转账凭证(选填):</view>
							<view class="input-box"><tui-upload :limit="2" :dirType="0" :userType="2" :serverUrl="serverUrl" @complete="result($event,'pubpay_img')" @remove="remove($event,'pubpay_img')"></tui-upload></view>
						</view>
						<view class="tip-txt">
							<view class="txt">流水号:</view>
							<view class="input-box"><input type="text" name="" v-model="callback_trade_no" placeholder="请输入凭证上的流水号或凭证号" ></view>
						</view>
						<view class="tip-txt">
							<view class="txt">公司名称：</view>
							<view class="input-box">广西瓯宁医疗科技有限公司</view>
						</view>
						<view class="tip-txt">
							<view class="txt">开户行：</view>
							<view class="input-box">兴业银行南宁分行</view>
						</view>
						<view class="tip-txt">
							<view class="txt">税号：</view>
							<view class="input-box">9145010006174381XR</view>
						</view>
						<view class="tip-txt">
							<view class="txt">账号：</view>
							<view class="input-box">552010100100607698</view>
						</view>
						<view class=" tip-btn" @tap.stop='copyText'>
							<view class="iconfont">
								&#xe661;
							</view>
							<view class="txt">
								复制
							</view>
						</view>
					</view>
					<view class="remarks-box">
						<textarea class="text-area" v-model="remark" placeholder="添加备注信息"></textarea>
					</view>
					<view style="height: 200rpx;"></view>
					
					

				</view>
				<!-- 底部固定栏 -->
				<view class="footer-fixed-box">
					<!-- <view class="left proxy" v-if="selectCashCode=='wechatFreePay'" key='wechatFreePay'>
						<radio @tap="agreedClick" style="transform:scale(0.6);margin-left: 0px;" :value="agreed" :checked="agreed" color='#69A4FE'></radio>
						<text>点击即同意</text><text @tap="news" class="green">《委托扣款授权书》</text>
					</view> -->
					<view class="left proxy"  key='wxPay'  @tap.stop="agreedClick">
						<radio style="transform:scale(0.6);margin-left: 0px;" :value="agreed" :checked="agreed" color='#69A4FE'></radio>
						<text>点击即同意</text><text @tap.stop="news" class="green">《小械械小程序电子销售协议》</text>
					</view>
					<view class="inner">
						<!-- +parseInt(data.usable_cash.status?0:data.list.cash) -->
						<view class="sum-text">合计:<text class="price-icon">￥</text>
							<text class="price-val"  v-if="related_type=='bargain'"> <!-- v-if="selectCashCode!='wechatFreePay'" -->
								{{deliver_type==0 && noDeliveFee>amount? parseFloat(amount+deliveFee.bargain-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}
							</text>
							<text class="price-val"  v-else-if="related_type=='batch'"> <!-- v-if="selectCashCode!='wechatFreePay'" -->
								{{deliver_type==0&& noDeliveFee>amount ? parseFloat(amount+deliveFee.batch-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}
							</text>
							<text class="price-val" v-else> 
								{{deliver_type==0  && noDeliveFee>amount ? parseFloat(amount+deliveFee.product-selectCoupon.coupon_money).toFixed(2):parseFloat(amount-selectCoupon.coupon_money).toFixed(2)}}
								
								<!-- {{ ( parseInt(data.list.amount[deliver_type])- parseInt(selectCoupon.coupon_money)-parseInt(data.list.cash)).toFixed(2)}}
								authFreeCash -->
							</text>
						</view>
						<view class="pay-row" v-if="selectedPayType =='pubpay'"><button class="pay-btn" @click="payClick">确认生成</button></view>
						<view class="pay-row" v-else ><button class="pay-btn" @click="payClick">确认支付</button></view>
					</view>

				</view>
			</view>

			<uni-popup ref="businessPayModel" type="center" >
				<view class="business-pay-temp">
					<view class="btn-close"><text class="close" @tap="$refs.businessPayModel.close()">x</text> </view>
					<view class="tip">请输入支付密码</view>
					<view class="temp-box">
						<!-- <view class="temp-left">：</view> -->
						<view class="temp-input">
							<!-- disabled -->
							<input
												type="number"
												v-for="(item, index) in code_len"
												:key="index"
												disabled
												@tap="onCode"
												:value="code_val.length >= index + 1 ? (code_val[index]!=''?'*': ''): ''"
												class="code-input-item flex-default-center"
											/>
							<!-- 实际监听 -->
							<input v-if="is_focus"  @blur="blurCode" @input="setCode" type="number" class="code-input" v-model="code_val" :maxlength="code_len" :focus="true"/>
							
							
						</view>
						
					</view>
					
					<view class="btn-pay" @tap="businessPay">
						确定支付
					</view>
					
					<view class="text">
						忘记密码？<text @tap="">点击修改</text>
					</view>
				</view>
			</uni-popup>
			
			<uni-popup ref="invoiceModal" type="bottom" >
				<scroll-view scroll-y="true"  class="invoice-temp">
					<view >
						<view class="title">
							<view class="title-txt">
								发票
							</view>
							<view class="closs">
								<text class="iconfont" @tap.stop="$refs.invoiceModal.close()">&#xe621;</text>
							</view>
						</view>
						<view class="fp">
							<view class="fp-title">
								发票类型
							</view>
							<view class="fp-btn">
								<view :class="invoice.type==0?'btn fp-btn-check':'btn '" @tap.stop='changefpType(0)'>
									不开发票
								</view>
								<view :class="invoice.type==1?'btn fp-btn-check':'btn '" @tap.stop='changefpType(1)'>
									普通发票
								</view>
								<view :class="invoice.type==2?'btn fp-btn-check':'btn '" @tap.stop='changefpType(2)'>
									专用发票
								</view>
								
							</view>
							<view class="tip" >
								订单完成后开具发票发送到邮箱
							</view>
						</view>
						<view class="" v-if="invoice.type">
							<view class="fp">
								<view class="fp-title">
									发票抬头 
								</view>
								<view class="fp-btn">
									<!-- <view class="btn">
										个人
									</view> -->
									<view class="btn fp-btn-check">
										单位
									</view>
								</view>
								<!-- <view class="fp-content" >
									<view class="temp">
										<view class="temp-row">个人名称*：</view>
										<view class="fp-init">
											<input type="text" v-model="name" />
											
										</view>
									</view>
								</view> -->
								
									<view class="fp-content">
										<view  class="temp" >
											<view class="temp-row">单位名称 <text>*</text>：</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.name"  placeholder="请输入单位名称" >
											</view>
										</view>
										<view class="temp">
											<view class="temp-row">纳税人识别号<text>*</text>：</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.credit_code"  placeholder="请输入纳税人识别号">
											</view>
										</view>
										<view  class="temp">
											<view class="temp-row">注册电话<text>*</text>：</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.phone" placeholder="请输入注册电话">
											</view>
										</view>
										<view  class="temp">
											<view class="temp-row">注册地址<text v-if="invoice.type>1">*</text>：</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.address" placeholder="请输入注册地址">
											</view>
										</view>
										<view class="temp">
											<view class="temp-row">开户银行<text v-if="invoice.type>1">*</text>：</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.deposit_bank" placeholder="请输入开户银行">
												
											</view>
										</view>
										
										<view class="temp">
											<view class="temp-row">银行账号<text v-if="invoice.type>1">*</text>：</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.bank_card" placeholder="请输入银行账号">
											</view>
										</view>
										<view  class="temp">
											<view class="temp-row">
												收票人电话*:
											</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.tel" placeholder="请输入收票人电话" >
											</view>
										</view>
										<view  class="temp">
											<view class="temp-row">
												收票人邮箱
											</view>
											<view class="fp-init">
												<input type="text" v-model="invoice.email"  placeholder="请输入收票人邮箱">
											</view>
										</view>
									</view>
									
								
							</view>
							
							
							<view class="fp">
								<view class="fp-title">
									发票内容
								</view>
								
								<view class="fp-btn">
									<view class="btn fp-btn-check">
										商品内容
									</view>
								</view>
							</view>
							<view style="color: #F44336;padding: 0 20rpx; ">
								注：开票时间一般为1~7个工作日，特殊情况可能会延期
							</view>
						</view>
						<view class="" style="height: 160rpx;">
							
						</view>
						<view class="btn-commit" @tap="invoiceCommit" :style="'bottom:calc(30rpx + '+pageBottom+'rpx)'">
							确定
						</view>
						
					
					</view>
								
				</scroll-view>
				
			</uni-popup>
	
			<!-- 优惠卷弹窗 -->
			<coupon-popup ref="couponPopup" :couponList='data.couponList' :show='showCouponPopup' :couponId='couponId'
			 @getOverAndSale='getOverAndSale' @maskClose='maskClose'>

				<view slot='close-coupon-popup' @click="closeCouponPopup">
					<text class="iconfont" style="font-size:32rpx;">&#xe693;</text>
				</view>

			</coupon-popup>
			<!-- 优惠卷弹窗end -->
			<!-- 提示弹框 -->
			<tui-tips ref="toast"></tui-tips>
			<!-- 登录弹框 -->
			<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />

		</view>
	</view>
</template>

<script>
	// cj引入优惠卷弹窗
	import couponPopup from "@/components/coupon-popup/coupon-popup"
	import {
		compare
	} from '@/utils/base.js' //降序函数
	// import tuiButton from "@/components/button/button"
	// import tuiListCell from "@/components/list-cell/list-cell"
	// import tuiBottomPopup from "@/components/bottom-popup/bottom-popup"
	// import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue'
	// import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import store from '@/store/index.js';
	import {oss_host} from '@/config/config.js';
	import cart from '@/utils/cartshop.js' 
	import tuiUpload from '@/components/tui-upload/tui-upload'
	//获取网络状态
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			uniPopup,
			tuiUpload,
			// tuiButton,
			// tuiListCell,
			// tuiBottomPopup,
			// mpvuePicker,
			// tuiSkeleton,
			couponPopup
			
		},
		computed: {
			//注册网络状态
			...mapGetters(['netWorkType','loginStatus'])
		},
		data() {
			return {
				// 图片链接站点
				OSS_HOST: oss_host,
				cashFreeState: false,
				showMaskloading: false,
				socketTask: null,
				screenHeight:750,
				pageBottom:'',
				// 确保websocket是打开状态
				is_open_socket: false,
				serverUrl:'',
				pubpay_img:[],
				callback_trade_no:'',
				current: 0,
				couponId: '',
				couponName: '',
				showCouponPopup: false,
				couponMoney: 0,
				skeletonShow: true,
				id: 53,
				token: '', //normsValue id
				skuL: '', // sku
				//配送方式
				deliver_type: 0,
				pick_user_name:'',//自提联系人
				pick_user_tel:'',//自提联系电话
				month_card_id: 8,
				hasCoupon: true,
				insufficient: false,
				selectCashCode: 'onlinePay',
				urls: ['/cash/pay', '/order/shopPay'],
				radioItems: [{
					value: 'wxpay',
					name: '微信支付'

				},
				{
					value: 'pubpay',
					name: '对公转账'
				
				}, 
				// {
				// 	value: 'businesspay',
				// 	name: '商户支付'
				// },
				],
				payType:{
					'wxpay':2,
					'pubpay':8,
					'businesspay':6
				},
				current: 0,//支付方式默认选中
				
				selectedPayType: 'wxpay',
				agreed: false, //同意代扣款协议
				
				product:[], //多产品
				type:'',//跳转方式 购物车 cart,确认清空购物车,  直接购买 '' 
				amount:0,//普通产品
				batch_amount:0,//采购总金额
				related_type:'',
				data: {
					user_id:'',
					list: {
						amount: [0, 0]
					},
					address: {


					},
					monthcard: {},
					//自提列表
					deliver_store: [],
					//配送设置
					deliver_option: {},
					couponList: [], //优惠券数据
					product: '',
					// usable_cash:{},
					usable_cash: {
						status: false,
						cash_code: ''

					},
					deliverStoreObj:{}
				},
				//下拉数据
				deliverStoreArray: [],
				// deliverStoreObj: {
				// 	text: '选择自提地址',
				// 	key: '',
				// 	val: ''
				// },
				pageStyle: 1,
				//备注
				remark:'',
				// 留言
				leavingAMessage: '',
				//使用的优惠券
				selectCoupon: {
					name: '可使用',
					coupon_money: 0,
					coupon_id: 0
				},
				timeoutObj: '',
				//成功支付金额
				payment:0,
				cartList:{},
				batchCartList:{},
				demandId:'',
				noDeliveFee:'',
				deliveFee:{},
				code_len: 6, // 长度
				code_val: '', // 值
				is_focus: false,
				is_pay:false,
				fp_type:0,//发票类型 0 1 2
				fp_type_name:'不开发票',
				invoice:{
					type:0,
					name:'', //公司名称
					credit_code:'',//纳税人识别号
					address:'',//公式地址,
					phone:'',//联系电话
					deposit_bank:'',//开户行,
					bank_card:'',//银行卡号
					
					email:'',//邮箱
					tel:'',
				},
				invoice_type1:{
					email:'',//邮箱
					tel:'',
				},
				invoice_type2:{
					email:'',//邮箱
					tel:'',
				}
			}	
		},
		onLoad: function(e) {
			const _this = this
			this.serverUrl = this.$service.getImgHost()
			if (typeof e.id != "undefined") {
				this.id = e.id
			}
			if (typeof e.month_card_id != "undefined") {
				this.month_card_id = e.month_card_id
			}
			if (typeof e.token != "undefined") {
				this.token = e.token
			}
			if (typeof e.sku != "undefined") {
				this.sku = e.sku
			}
			if (typeof e.norms_value_id != "undefined") {
				this.norms_value_id = e.norms_value_id
			}
			if (typeof e.product != "undefined") {
				this.product = e.product
			}
			if (typeof e.type != "undefined") {
				this.type = e.type
			}
			if(typeof e.demandId !='undefined'){
				this.demandId = e.demandId
			}
			
			for(let item of JSON.parse(this.product))
			{
				// console.log(key.norms_value_id)
				this.related_type = 'batch';
				if(typeof item.bargainId !='undefined'){
					this.related_type = 'bargain';
					
				}
				
			}
			if(typeof e.related_type!="undefined"){
				this.related_type = e.related_type;
			}
			console.log('******related_type',this.related_type)
			this.cartList = uni.getStorageSync('cartList')==''?{}:JSON.parse(uni.getStorageSync('cartList'))
			this.batchCartList = uni.getStorageSync('batchCartList')==''?{}:JSON.parse(uni.getStorageSync('batchCartList'))
			// this.showMaskloading = true;
			// this.connectSocketInit();
			//获取满屏高度
			uni.getSystemInfo({
			    success: function (res) {
			        _this.screenHeight = res.screenHeight
					_this.pageBottom = res.safeAreaInsets.bottom *2 //底部刘海
			    }
			});
			_this.deliver_type =uni.getStorageSync('deliver_type')?uni.getStorageSync('deliver_type'):0
		},
		onShow() {
			const _this = this;
			
			if(uni.getStorageSync('project_user_id')){
				_this.data.user_id=JSON.parse(uni.getStorageSync('project_user_id')).user_id;
			}
			// this.product='[{"id":"67","norms_value_id":97,"num":1},{"id":"69","norms_value_id":99,"num":2}]'
			// wx.setNavigationBarColor({
			// 	frontColor: '#ffffff',
			// 	backgroundColor: '#69A4FE',
			// 	animation: {
			// 		duration: 400,
			// 		timingFunc: 'easeIn'
			// 	}
			// })
			//console.log(_this.type)
			//获取订单信息
			var opt = {
				url: '/product/payDetail',
				data: {
					product:this.product
					// id:53,
					// month_card_id:8
				},
				success: function(res) {
					console.log(res)


					if (res.status == 1) {
						_this.data.list = res.data.list
						_this.amount =res.data.amount
						_this.batch_amount =res.data.batch_amount;
						_this.noDeliveFee = res.data.noDeliveFee
						_this.deliveFee=res.data.deliveFee
						// _this.data.deliverStoreObj = res.data.store
						// _this.data.deliverStoreObj.store_name =res.data.store.name
						_this.data.deliver_option = res.data.deliver_option
						//初始配送方式
						// _this.deliver_type = res.data.deliver_option.deliver_type
						_this.deliverStoreArray = []
						_this.data.coupon = res.data.coupon
						_this.data.usable_cash = res.data.usable_cash
						// 采购员 状态
						_this.data.buyerEstate = res.data.buyerEstate
						_this.data.userInfo = res.data.userInfo
						_this.data.invoice =res.data.invoice
						_this.data.invoice.forEach((item)=>{
							if(item.type == 1){
								_this.invoice_type1.type = item.type
								_this.invoice_type1.ele_accept = item.ele_accept
								_this.invoice_type1.name = item.name
								_this.invoice_type1.credit_code = item.credit_code
								_this.invoice_type1.address = item.address
								_this.invoice_type1.invoice_type = item.invoice_type
								_this.invoice_type1.phone=item.phone 
								_this.invoice_type1.deposit_bank = item.deposit_bank
							}else if(item.type == 2){ 
								_this.invoice_type2.type=item.type,
								_this.invoice_type2.ele_accept=item.ele_accept,
								_this.invoice_type2.name=item.name,
								_this.invoice_type2.credit_code=item.credit_code,
								_this.invoice_type2.address=item.address, 
								_this.invoice_type2.phone=item.phone 
								_this.invoice_type2.bank=item.bank 
								_this.invoice_type2.bank_card=item.bank_card 
								_this.invoice_type2.deposit_bank = item.deposit_bank
								
							}   
						})
						//构造提货点下拉数据
						// res.data.deliver_store.forEach(function(v, k) {
						// 	let data = {
						// 		label: v.name,
						// 		value: v.id
						// 	}
						// 	//console.log(_this.data.valueArray)
						// 	_this.deliverStoreArray.push(data)
						// })

						_this.skeletonShow = false

					}

				},

			};
			//登陆状态才远程访问资源
			_this.$service.GetApi(opt)
			uni.getStorage({
				key: 'selectCoupon',
				success: (e) => {
					_this.selectCoupon = e.data
				}
			})
			uni.getStorage({
				key: 'seleteStore',				
				success: (e)=> {
					console.log('***配送store:',e)
					_this.data.deliverStoreObj =e.data
					console.log('***配送store2:',_this.data.deliverStoreObj)
					
				}
			})
			//设置默认地址
			uni.getStorage({
				key: 'selectAddress',
				success: (e) => {
					this.data.address = e.data;
					console.log(e)

				},
				fail: () => {
					//初始默认地址

					var opt = {
						url: '/address/defaultAddress',
						success: function(res) {
							//console.log(res)
							if (res.status == 1) {
								_this.data.address = res.data.address

							} else {

							}

						}
					};
					_this.$service.GetApi(opt)
				}
			})


		},
		methods: {
			news() {
				let _this = this;
				_this.$refer.setVilit('/packageUser/pages/my/new/index')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				
				_this.$refer.toUrl(callback)
				return
			},
			copyText() {
				let  text = '公司名称：广西瓯宁医疗科技有限公司\n开户行：兴业银行南宁分行\n税号：9145010006174381XR\n账号：552010100100607698'
			      uni.setClipboardData({	
			        data: text,
			        success: function () {
			          uni.showToast({
			            title: '复制成功',
			            icon: 'success',
			            duration: 2000
			          });
			        }
			      });
			},
			result: function(e,name) {
				console.log(e)
				
				this.pubpay_img = e.imgNameArr;
				
				
				console.log(this.pubpay_img,'******')
				// uni.setStorageSync('business_license', JSON.stringify(this.imageData));
			},
			remove: function(e,name) {
				//移除图片
				console.log(e)
				let index = e.index
				this.pubpay_img.splice(index, 1);
				console.log(this.pubpay_img,'******')
			},
			// 发票 star
			showChangeInvoice(){
				let  _this = this
				_this.$refs.invoiceModal.open(); 
			},
			changefpType(type){
				let _this = this 
				_this.invoice.type = type
				switch (_this.invoice.type){
					case 1:
						_this.invoice = _this.invoice_type1
						_this.invoice.type = type
						break;
					case 2:
						_this.invoice = _this.invoice_type2
						_this.invoice.type = type
						break;
					default:
						_this.invoice ={}
						_this.invoice.type = 0
						break;
				}
				
			},
			invoiceCommit(){
				let _this = this
				if(_this.invoice.type){
					if(_this.invoice.name == '' || _this.invoice.credit_code == '' ||  _this.invoice.phone==''){
						uni.showToast({
							icon:'none',
							title:'请输入抬头信息'
						})
						return ;
					}
					if(_this.invoice.tel==''){
						uni.showToast({
							icon:'none',
							title:'请输入收票人信息'
						})
						return ;
					}
					if(_this.invoice.type>=1){
						
						if(_this.invoice.address=='' ){
							uni.showToast({
								icon:'none',
								title:'请输入注册地址信息'
							})
							return ;
						}
						if(_this.invoice.phone==''){
							uni.showToast({
								icon:'none',
								title:'请输入收票人信息'
							})
							return ;
						}
						if(_this.invoice.deposit_bank==''){
							uni.showToast({
								icon:'none',
								title:'请输入开户行'
							})
							return ;
						}
						if(_this.invoice.bank_card==''){
							uni.showToast({
								icon:'none',
								title:'请输入卡号'
							})
							return ;
						}
					}
					
				}
				switch(_this.invoice.type){
					case 0:
						_this.fp_type_name = '不开发票'
					break;
					case 1:
						_this.fp_type_name = '普通发票'
					break;
					case 2:
						_this.fp_type_name = '专用发票'
					break;
				} 
				_this.$refs.invoiceModal.close(); 
			},
			//订阅消息 用户允许后才能发 最多3个
			payClick() {
				let _this = this
				// this.agreed = !this.agreed;
				if(!_this.deliver_type){
					uni.requestSubscribeMessage({
					  tmplIds: [
						  'diiQ4zMTrAVqgjK0kA1IHaVSEzDiRMrxXwPOA009kk4',
						  // 'PS-EKzqEghm53kiXBDF7aKDZPa_sdr9pLXMebk7TEf0',
						  // 'xZqN1yl__-vk-u78pNfVgGq_qhxgnoaodKI5LxKoVzI'
						  ],
					  success (res) {
						  console.log(2222)
						  console.log(res)
					  },
					  complete(){
						  // 接口调用结束的回调函数（调用成功、失败都会执行）
						  _this.pay()
					  }
					})
				}else{
					_this.pay()
				}
				
			},
			changeDeliverType(type){
				this.deliver_type=type
				uni.setStorageSync('deliver_type', type)
			},
			backFun(){
				uni.navigateBack({
					delta: 1
				})
			},
			setCode(e) {
				this.code_val = e.detail.value;
			},
			onCode() {			
				this.is_focus = true;
			},
			blurCode() {
				this.is_focus = false;
			},
			// 关闭优惠卷弹窗
			closeCouponPopup() {
				this.showCouponPopup = false;
			},
			maskClose(data) {
				this.showCouponPopup = data;
			},
			getOverAndSale(data) {
				// 点击子组件传过来的值
				this.showCouponPopup = false;
				this.selectCoupon.name = data.name;
				if(this.couponId == data.id){
					this.selectCoupon.coupon_money = 0;
					
					this.couponId = 0;
				}else{
					this.selectCoupon.coupon_money = data.coupon_money;
					
					this.couponId = data.id;
				}
				


			},
			// 刷新的方法
			refresh() {
				window.addEventListener('pageshow', this.onShow);
			},



			chooseAddr() {
				// uni.navigateTo({
				// 	url: "../address/address"
				// })
				const _this = this
				_this.$refer.setVilit('/packageUser/pages/user/address/address')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				_this.$refer.toUrl(callback)
			},
			// 获取优惠卷列表
			getCouponList() {
				let _this = this;
				_this.couponList = [];
				let couponObj = _this.data.list; //根据这里的价格过滤优惠券 [{}] 产品信息（多产品）
				// let packagePrice= parseFloat(couponObj.package_price);//x
				// let deliverFee=parseFloat(couponObj.deliver_fee);//x
				let oldPrice = parseFloat(_this.amount); //不包含运费  运费独立计算
				// 可叠加状态
				let opt = {
					url: '/coupon/canUseCoupon',
					data: {
						// related_type:1, //产品类型,配送租赁传1
						// related_id: couponObj.id, //产品id
						// store_id: '' //门店id
					},
					success: function(res) {
						//console.log(res)
						if (res.status == 1) {
							let result = [];
							let overReduce = []; //满减叠加
							let saleReduce = []; //折后可叠加
							let overAndSale = []; //满减和折后组合数组
							let finallyList = [];
							let relatedType = 5;//当前业务线 5,7,8
							// limit_type 0无限制 1类别可用2单品3自定义4门店5核销门店
							// type  0满减 1折扣
							// is_overlay 是否可叠加 0 否 1是
							if (res.data.list.length) {
								// 1过滤掉达不到使用优惠卷和满减的数据
								// result = res.data.list.filter(function(row) {
								// 	return oldPrice >= row.spend_money

								// })
								res.data.list.forEach(function(v){
									switch(v.limit_type){// 优惠券类型
										case 0:	//无门槛
											
											if(oldPrice >= v.spend_money){
												if (v.type == 1) {
													
													v.coupon_money = (oldPrice - oldPrice * (parseFloat(v.coupon_money))).toFixed(2); //折扣金额
												}
												result.push(v)
											}
											break;
										case 1: // 类别可用  参考order. related_type 不是产品分类
											if(_this.related_type == 'batch'){
												relatedType = 8;
											}else if(_this.related_type == 'product'){
												relatedType = 5;
											}else{
												relatedType = 7;
											}
											if(v.related_type == relatedType){
												if (v.type == 1) {
													
													v.coupon_money = (oldPrice - oldPrice * (parseFloat(v.coupon_money))).toFixed(2); //折扣金额
												}
												result.push(v)
											}
											break;
										case 2:// 单品 特定
											if(_this.related_type == 'batch'){
												relatedType = 8;
											}else if(_this.related_type == 'product'){
												relatedType = 5;
											}else{
												relatedType = 7;
											}
											let amount =0;
											let ids = v.related_id.split(',');
											let inIds = false
											if(v.related_type == relatedType){
												// indexOf   99,9,12,13    1 返回的不是-1
												couponObj.forEach(function(item){
													inIds = false
													ids.forEach(function(id){
														if(id == item.id) inIds=true;
													});
													// console.log('***inIds',inIds)
													if(inIds){ 
														if(relatedType == 5){
															amount+=item.price*item.num
														}else if(relatedType == 8){
															amount+=item.batch_price*item.num
														}
														
													}
												});
												// console.log(22222222,amount)
												// console.log('***',v.spend_money)
												if(amount >= v.spend_money){
													if (v.type == 1) {
														// 符合要求产品总金额
														v.coupon_money = (amount - amount * (parseFloat(v.coupon_money))).toFixed(2); //折扣金额
													}
													result.push(v)
												}
											}
											break;
										case 3:// 自定义产品 暂时不用
											
											break;
										case 4: //门店 符合门店
											let storeIds = v.store_id.split(',');
											let storeAmount = 0;
											let inStore = false;
											// 计算符合要求的商品总额  
											couponObj.forEach(function(item){
												
												inStore = false
												storeIds.forEach(function(id){
													if(id == item.store_id) inStore=true;
												});
												// console.log('***inIds',inIds)
												if(inStore){ 
													if(relatedType == 5){
														storeAmount+=item.price*item.num
													}else if(relatedType == 8){
														storeAmount+=item.batch_price*item.num
													}
													
												}
													
											
												// 这个不严谨   1   在 11,12,12,31 返回的是0 
												// if(storeAmount.indexOf(item.store_id) !=-1){
												// 	if(relatedType == 5){
												// 		storeAmount+=item.price*item.num
												// 	}else if(relatedType == 8){
												// 		storeAmount+=item.batch_price*item.num
												// 	}
													
												// }
											});
											// console.log('2******storeAmount',storeAmount)
											if(storeAmount >= v.spend_money){
												if (v.type == 1) { //折扣计算  先折扣后满减
													// 符合要求产品总金额
													v.coupon_money = (storeAmount - storeAmount * (parseFloat(v.coupon_money))).toFixed(2); //折扣金额
												}
												result.push(v)
											}
											break;
										case 5://线下门店核销 线下使用的
										
											break;
									}
									
								});
							}
							
							// console.log('*********',result)
							// return;
							// result.forEach(function(cv) {
							// 	if (cv.type == 1) {
									
							// 		cv.coupon_money = (oldPrice - oldPrice * (parseFloat(cv.coupon_money))).toFixed(2); //折扣金额
							// 	}
							// })
							overReduce = result.filter((res) => {
								// 满减可叠加数组
								return res.type == 0 && res.is_overlay == 1
							})
							saleReduce = result.filter((res) => {
								// 折扣可叠加数组
								return res.type == 1 && res.is_overlay == 1
							});
							// 先折扣 后满减
							overReduce.forEach(function(res, i) {
								saleReduce.forEach(function(item) {
									// 后面可以在这里过滤组合,折扣后的价格达不到满减的  item.coupon_money 折扣 ↑上边已计算出结果
									let afterSalePrice = (oldPrice  - (parseFloat(item.coupon_money))).toFixed(2); //折扣后的价格
									// console.log('***afterSalePrice',afterSalePrice)
									// console.log('***res.spend_money', res.spend_money)
									let overPrice = parseFloat(res.coupon_money); //满减券
									let salePrice = parseFloat(item.coupon_money); //折扣金额
									let sumCoupon = (salePrice + overPrice).toFixed(2); //总的优惠金额
									if (afterSalePrice*100 >= res.spend_money*100) {
										// console.log(11111111,afterSalePrice,'**',res.spend_money)
										overAndSale.push({
											overSaleList: [res, item],
											id: [item.id, res.id].join(','),
											tag_name: '组合券',
											name: item.name + '\n' + res.name,
											related_type_names: res.related_type_names,
											coupon_money: sumCoupon,
											use_start_at: res.use_start_at,
											use_expire_at: res.use_expire_at
										})
									}
								})
							});
							// console.log('******overAndSale',overAndSale) 
							finallyList = JSON.parse(JSON.stringify(result))
							// 将可叠加的满减和折扣进行组合 暂时取消组合券
							// finallyList.push(...overAndSale);
							// console.log(finallyList)
							// 新增条件
							let createArr=[];
							finallyList.forEach(function(row){
								// 月卡 related_type=2   配送  1,此处默认1
								if(row.limit_type==0){
									// 0全部可用
									createArr.push(row)
								}else if(row.limit_type==1){
									//  related_type != 产品的类别 剔除
									if(row.related_type==1){
										//related_type此处默认1
										createArr.push(row)
									}

								}
								else if(row.limit_type==2){
									//条件A:（优惠券）related_type !=产品的类别,条件B:(产品) id 优惠券）在 related_id(1,2,3)
									//不满足A直接剔除
									//满足A的情况下，条件B不满足，剔除
									let related_id_arr=[];
									related_id_arr=row.related_id.split(',');
									console.log(related_id_arr)
									console.log(_this.data.list.id)
									// console.log(related_id_arr.indexOf(_this.data.list.id.toString()))
									// if(row.related_type==1 && related_id_arr.indexOf(_this.data.list.id.toString())>=0){
										console.log(5656)
										createArr.push(row)
									// }
								}else{
									// 组合券
									createArr.push(row)
								}

							})
							createArr.sort(compare('coupon_money'));
							_this.data.couponList = JSON.parse(JSON.stringify(createArr))
						} else {
							let options = {
								msg: res.message,
								type: 'danger'
							};
							_this.$refs.toast.showTips(options);
						}
					}
				}
				_this.$service.GetApi(opt)
			},
			// 跳转选择优惠卷
			useCoupon() {

				this.showCouponPopup = true;
				this.getCouponList();
				// const _this = this

				// if(type=='coupon'){
				// 	_this.$refer.setVilit('/pages/user/coupon/coupon')
				// 	let callback = function(url){
				// 	  _this.$refs.popupvLogin.open()
				// 	}
				// 	  var data={
				// 	      buyStatus:1,
				// 		  payment:_this.data.list.amount[_this.deliver_type]
				// 	  }
				// 	_this.$refer.toUrl(callback,data)
				// }
			},
			//选择收货地址
			selectAddress() {
				// uni.navigateTo({
				// 	url:'/pages/user/address/address?type=select'
				// })
				const _this = this
				//门店自提
				if(_this.deliver_type ==1){
					// uni.showToast({
					//   title: '开发中，尽情期待！',
					//   icon: 'none'
					// })
					// return ;
					_this.data.deliver_store
					_this.$refer.setVilit('/pages/PayOrder/deliverStore')
					let callback = function(url) {
						_this.$refs.popupvLogin.open()
					}
					var data = {
						type: 'select',
						// product_id:this.id,
						lat1:uni.getStorageSync('loginlatitude'),
						lng1:uni.getStorageSync('loginlongitude')
						
					}
					_this.$refer.toUrl(callback, data)
				}else{
					_this.$refer.setVilit('/pages/address/address')
					let callback = function(url) {
						_this.$refs.popupvLogin.open()
					}
					var data = {
						type: 'select'
						
					}
					_this.$refer.toUrl(callback, data)
				}
				
				
				
			},
			changePayType(item,index){
				let _this = this
				_this.current = index,
				_this.selectedPayType = item.value
			},
			//支付提交
			pay() { 
				
				//微信支付走下面
				let _this = this
				let dataObj = {}
				let payList = []
				
				let goods={}
				if(!_this.agreed){
					uni.showToast({
						icon:'none',
						title:'请阅读查看销售协议，同意即生效',
						duration:5000
					})
					return 
				}
				// console.log(_this.data.buyerEstate)
				if(_this.related_type == 'batch'  && !_this.data.buyerEstate){
					uni.showToast({
						icon:'none',
						title:'您的证件信息已过期，请前往个人中心<设置>更新资质信息',
						duration:5000
					})
					return 
				}
				if(_this.deliver_type  == 1){
					if(_this.pick_user_name == '' || _this.pick_user_tel==''){
						uni.showToast({
							icon:'none',
							title:'请输入联系人和联系电话！',
							// duration:5000
						})
						return ;
					}
				}
				for(let item of JSON.parse(this.product))
				{
					// console.log(key.norms_value_id)

					if(typeof item.bargainId !='undefined'){
						goods = {
							 type: 'bargain',
							 pay_type: _this.payType[_this.selectedPayType],
							 id:item.bargainId
							 // number:item.num,
							 // product_id:item.product_id,
							 // norms_value_id:item.norms_value_id,
						}
					}else{
						goods = {
							 type: _this.related_type,
							 pay_type: _this.payType[_this.selectedPayType],
							 number:item.num,
							 product_id:item.id,
							 norms_value_id:item.norms_value_id,
							 demandId:_this.demandId||''//处方  问诊号
						}

					} 
					payList.push(goods)
				}
				dataObj = {
					deliver_type: _this.deliver_type,
					payList:payList,
					remark:this.remark,					
					pay_type:_this.payType[_this.selectedPayType],
					invoice:_this.invoice,
					callback_trade_no:_this.callback_trade_no,
					pubpay_img:_this.pubpay_img,
				}
				
				dataObj.coupon_id = this.couponId;
				let title = '';
				if (dataObj.deliver_type == 0) {
					dataObj.deliver_address =_this.data.address.province_name? _this.data.address.province_name + _this.data.address.city_name + _this.data.address.area_name +
						_this.data.address.detail:''
					dataObj.deliver_name = _this.data.address.name
					dataObj.deliver_tel = _this.data.address.tel
					dataObj.deliver_store_id = 0
					title ='请选择收货地址' 
				} else {
					dataObj.deliver_address =_this.data.deliverStoreObj.store_name? _this.data.deliverStoreObj.store_name:''
					dataObj.deliver_store_id = _this.data.deliverStoreObj.id
					dataObj.deliver_name = _this.pick_user_name||''
					dataObj.deliver_tel = _this.pick_user_tel
					title ='请选择自提门店' 
				}
				// console.log(dataObj.deliver_address)
				if(dataObj.deliver_address ==''||dataObj.deliver_address ==NaN ){
					uni.showToast({
						icon:'none',
						title:title
					})
					return 
				}
				// 测试
				// console.log(dataObj)
				// return;
				
				
				
				// console.log(_this.data.child)
				var opt = {
					url: '/product/wxPay',
					data:dataObj,
					success: function(res) {
						if (res.status == 1) {
							// _this.showMaskloading = false;
							uni.setStorage({
								key: "payment_id",
								data: res.data.list.payment_id //需要存储的数据
							})
							// _this.refunTime = setInterval(() => {
							// 	console.log('successTime轮询---')
							// 	// 取消订单
							// 	_this.cannelOrderEstate();
							// },600000) 
							console.log('pay_type******',_this.selectedPayType)
							if(_this.selectedPayType=='businesspay'){
								// _this.$refs.businessPayModel.open()
								// console.log(123456)
								_this.$refs.businessPayModel.open()
							}else if(_this.selectedPayType=='pubpay'){
								if(_this.type == 'cart' ){
									payCartList.forEach(function(v){
										// console.log('*****v',v)
										//删除购物车商品
										let goods = {norms_value_id:v.norms_value_id,store_id:v.store_id}  
										
										cart.delProd(goods,_this.cartList,function(res){
											uni.setStorageSync('cartList',JSON.stringify(res.data.cartList))
											_this.cartList = res.data.cartList
										});
									})
									uni.setStorageSync('payCartList',JSON.stringify({}))
									
								}
								_this.$refer.setVilit('/pages/PayOrder/success');
								let data = {
									course:0
								}
								let callback = function(url) {
								
								}
								_this.$refer.toUrl(callback, data,'reLaunch')
							}
							else{
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: res.data.list.timeStamp,
									nonceStr: res.data.list.nonce_str,
									package: 'prepay_id=' + res.data.list.prepay_id,
									signType: 'MD5',
									paySign: res.data.list.paySign,
									success: function(res) {
										
										
											
										if (res.errMsg == 'requestPayment:ok') {
										
											_this.showMaskloading = true;
											//支付成功清除购物车
											let payCartList = JSON.parse(_this.product)
											// console.log('***',payCartList)
											if(_this.type == 'cart' ){
												payCartList.forEach(function(v){
													// console.log('*****v',v)
													//删除购物车商品
													let goods = {norms_value_id:v.norms_value_id,store_id:v.store_id}  
													
													cart.delProd(goods,_this.cartList,function(res){
														uni.setStorageSync('cartList',JSON.stringify(res.data.cartList))
														_this.cartList = res.data.cartList
													});
												})
												uni.setStorageSync('payCartList',JSON.stringify({}))
												
											}
											if(_this.type == 'batchCard'){
												// 采购购物车
												uni.setStorageSync('batchCartList',JSON.stringify({}))
											}
											_this.successTime = setInterval(() => {
												console.log('successTime轮询---')
												_this.checkShopOrderEstate();
											}, 2000) 
										}
											
									},
									fail: function(err) {
										console.log(322)
										_this.cancelOrder()
										if(	_this.successTime != ''){
											clearInterval(_this.successTime);
											_this.successTime = '';
										}
									 
									}
								});
											
											
							}
							
							
			
						} else {
							let options = {
								msg: res.message,
								type: 'danger'
							};
							_this.$refs.toast.showTips(options);
							return
						}
			
					}
				};
			
				if (this.loginStatus) {
					this.$service.GetApi(opt) //网络
				}
			
			},
			businessPay(){
				let _this = this
				_this.showMaskloading =true
				_this.businessPayModel =false
				
				// console.log('payment_id轮询---', uni.getStorageSync('payment_id'))
				var opt = {
					url: '/product/businessPay',
					data: {
						pay_password:_this.code_val,
						payment_id: uni.getStorageSync('payment_id')
					},
					success: function(res) {
						if (res.status == 1) {
							_this.showMaskloading = false;
							clearInterval(_this.successTime); //关闭轮询
							_this.successTime = '';
							// console.log(res.message)
							uni.removeStorageSync('payment_id');
							if(_this.type == 'batchCard'){
								// 采购购物车
								uni.setStorageSync('batchCarList',JSON.stringify({}))
							}
							let list = res.data.list;
							_this.$refer.setVilit('/pages/PayOrder/success');
							let data = {
								course:0
							}
							let callback = function(url) {
							
							}
							_this.$refer.toUrl(callback, data,'reLaunch')
						} else {
							_this.businessPayModel =true
							uni.showToast({
								icon:'error',
								title:'密码错误'
							})
							console.log(res.message)
						}
							
					}
				}
				_this.$service.GetApi(opt)
			},
			cancelOrder(){
				// 用户取消支付 取消订单
				let _this = this
				// console.log('payment_id轮询---', uni.getStorageSync('payment_id'))
				var opt = {
					url: '/order/cancelOrder',
					data: {
						id: uni.getStorageSync('payment_id')
					},
					success: function(res) {
						if (res.status == 1) {
							// 取消成功
							console.log(res)
							
							
						} else {
							console.log(res.message)
						}
							
					}
				};
							
				if (this.loginStatus) {
					this.$service.GetApi(opt) //网络
				}
			},
			// 
			checkShopOrderEstate() {
				let _this = this
				// console.log('payment_id轮询---', uni.getStorageSync('payment_id'))
				var opt = {
					url: '/order/checkShopOrderEstate',
					data: {
						payment_id: uni.getStorageSync('payment_id')
					},
					success: function(res) {
						if (res.status == 1) {
							_this.showMaskloading = false;
							clearInterval(_this.successTime); //关闭轮询
							_this.successTime = '';
							// console.log(res.message)
							uni.removeStorageSync('payment_id');
							let list = res.data.list;
							
							_this.$refer.setVilit('/pages/PayOrder/success');
							let data = {
								course:1
							}
							let callback = function(url) {
			
							}
							
							_this.$refer.toUrl(callback, data,'reLaunch')
							
							
						} else {
							console.log(res.message)
						}
			
					}
				};
			
				if (this.loginStatus) {
					this.$service.GetApi(opt) //网络
				}
			},
			
			
			agreedClick() {
				this.agreed = !this.agreed;
				// if (this.agreed && this.selectCashCode == 'wechatFreePay') {

				// 	this.authFreeCash()
				// }
			},
			cashRadioChange: function(e) {

				this.selectCashCode = e.target.value;
				this.agreed = false;


			},
			freeCashHttp(res) {
				let _this = this

				if (wx.openBusinessView) {
					wx.openBusinessView({
						businessType: 'wxpayScoreUse',
						extraData: {
							mch_id: res.data.list.mch_id,
							package: res.data.list.package,
							timestamp: res.data.list.timestamp,
							nonce_str: res.data.list.nonce_str,
							sign_type: 'HMAC-SHA256',
							sign: res.data.list.sign
						},
						success() {
							// console.log('授权12')
							//启动支付加载
							_this.showMaskloading = true;

							// websocket,传加密的用户id
							_this.connectSocketInit();


						},
						fail() {
							//dosomething
							//console.log(2)
							_this.cashModal = true
						},
						complete() {
							//dosomething
						}
					})
				} else {
					//引导用户升级微信版本
				}
			},
			authFreeCash() {
				// console.log(11)
				let _this = this;
				// if (!_this.selectCashCode) {
				// 	let options = {
				// 		msg: '请选择押金支付方式',
				// 		type: 'danger'
				// 	};
				// 	_this.$refs.toast.showTips(options);
				// 	return
				// }
				// if (!_this.agreed && _this.selectCashCode == 'wechatFreePay') {
				// 	let options = {
				// 		msg: '请同意委托扣款授权书',
				// 		type: 'danger'
				// 	};
				// 	_this.$refs.toast.showTips(options);
				// 	return
				// }

				if (_this.deliver_type == 0) {
					//送货上门
					if (!_this.data.address.id > 0) {
						let options = {
							msg: '收货地址必须',
							type: 'danger'
						};
						_this.$refs.toast.showTips(options);
						return
					}
				}
				if (_this.deliver_type == 1) {
					//自提
					// console.log(_this.deliverStoreObj.val)
					if (!_this.data.deliverStoreObj.id > 0) {
						let options = {
							msg: '提货地址必须',
							type: 'danger'
						};
						_this.$refs.toast.showTips(options);
						return
					}
				}
				// #ifdef  MP-WEIXIN || APP-PLUS
				// 根据免押状态决定传参和接口地址
				let url = '';
				let dataObj = {};
				if (_this.selectCashCode == 'wechatFreePay') {
					// 免押支付
					if(parseInt(_this.data.list.cash)>499){

						_this.agreed=false;
						let options = {
							msg: '超出授权免押金额',
							type: 'danger'
						};
						_this.$refs.toast.showTips(options);

						_this.$forceUpdate();
						return
					}
					url = _this.urls[0];
					dataObj = {
						scene: 'order',
						trade_no: 'order', //交易单号
						cash_code: 'wechatFreePay',
						token: this.token,
						id: _this.id //产品id
					}
					dataObj.cash_service = 'online'
				} else {
					
					url = _this.urls[1];

					// console.log(_this.token)
					 dataObj = {
						deliver_type: _this.deliver_type,
						month_card_id: _this.month_card_id,
						//留言
						// leaving_a_message:leavingAMessage,
						id: _this.id,
						coupon_id: this.selectCoupon.coupon_id,
						token: this.token,
						remark:this.remark,
						scene:'order'


					}

					dataObj.coupon_id = this.couponId;
					dataObj.cashStatus  = _this.data.usable_cash.status == true?'pay':'noPay';
					dataObj.cash_code = 'onlinePay'
					dataObj.scene = 'order'
					if (dataObj.deliver_type == 0) {
						dataObj.deliver_address = _this.data.address.province_name + _this.data.address.city_name + _this.data.address.area_name +
							_this.data.address.detail
						dataObj.deliver_name = _this.data.address.name
						dataObj.deliver_tel = _this.data.address.tel
						dataObj.deliver_store_id = 0
					} else {
						dataObj.deliver_address = _this.data.deliverStoreObj.store_name
						dataObj.deliver_store_id = _this.data.deliverStoreObj.id
						dataObj.deliver_name = ''
						dataObj.deliver_tel = ''
					}

				}

				var opt = {
					url: url, //免押接口，不免押金走product/rent
					data: dataObj,
					success: function(res) {
						// console.log(res)
						if(res.status ==1){
							store.dispatch('setOrderNo', res.data.list.order_no)
							store.dispatch('setTradeNo', res.data.list.trade_no)
							store.dispatch('setUserId', res.data.list.user_id)
						}
						
						if (res.status ==1 && _this.selectCashCode == 'wechatFreePay') {
							_this.cashFreeState=true;
							_this.freeCashHttp(res)

						}if (res.status ==1 && res.data.list.pay_type == 'pay') {
							//微信支付接口
						// #ifdef  H5
							_this.payment = res.data.list.payment
							jweixin.chooseWXPay({
							  timestamp: res.data.list.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
							  nonceStr: res.data.list.nonce_str, // 支付签名随机串，不长于 32 位
							  package: 'prepay_id='+res.data.list.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
							  signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
							  paySign: res.data.list.paySign, // 支付签名
							  success: function (res) {
									//支付成功
									//console.log('success:' + JSON.stringify(res));
										if(res.errMsg=='requestPayment:ok'){
										//console.log(111)
											//跳转至支付成功
											//清理使用的优惠券
											uni.removeStorage({
												key: 'selectCoupon'
											})


											// let url=_this.$refer.setVilit('/packageOnline/pages/order/success/success')
											let url=_this.$refer.setVilit('/packageUser/pages/user/pay/pay-success')


											let callback = function(url) {
												_this.$refs.popupvLogin.open()
											}
											var data = {
												amount: res.data.list.payment,
												store_name:'',
												product_name:_this.data.list.name,
												price:_this.data.list.price,
												// period_use_day:_this.data.list.period_use_day
											}
											_this.$refer.toUrl(callback, data, 'reLaunch')
											return

										}
									}
								});
							// #endif

							// #ifdef  MP-WEIXIN  || APP-PLUS
							_this.payment = res.data.list.payment
							// _this.order_no = res.data.list.order_no

							// #ifdef  APP-PLUS

							const orderInfo = JSON.stringify({
								appid: res.data.list.appid,
								noncestr: res.data.list.nonce_str,
								package: 'Sign=WXPay',
								partnerid: res.data.list.partnerid,
								prepayid: res.data.list.prepay_id,
								timestamp: res.data.list.timeStamp,
								sign: res.data.list.sign.substring(0, 30),
							})
							// #endif
							uni.requestPayment({
								provider: 'wxpay',
								// #ifdef  MP-WEIXIN
								timeStamp: res.data.list.timeStamp,
								nonceStr: res.data.list.nonce_str,
								package: 'prepay_id=' + res.data.list.prepay_id,
								signType: 'MD5',
								paySign: res.data.list.paySign,
								// #endif
								// #ifdef  APP-PLUS
								orderInfo: orderInfo,
								// #endif
								success: function(res) {

									if (res.errMsg == 'requestPayment:ok')
									{
										//清理使用的优惠券
										uni.removeStorage({
											key: 'selectCoupon'
										})
										// let url= _this.$refer.setVilit('/pages/pay/success/success');
										let url= _this.$refer.setVilit('/packageUser/pages/user/pay/pay-success');
										let callback = function(url) {
											_this.$refs.popupvLogin.open()
										}
										var data = {
											amount: _this.payment,
											product_name:_this.data.list.name
										}

										_this.$refer.toUrl(callback, data, 'reLaunch')

										return


									}

								},
								fail: function(err) {
									var opt = {
										url: '/coupon/clearCoupon',
										data: {
											order_no: store.getters.orderNo
											// order_no:"202010171849465f8acc4a24cca"
										},
										success: function(res) {

										},
									}

									_this.$service.GetApi(opt);
								}
							});
							// #endif
								return
						} if (res.status ==1 && res.data.list.pay_type == 'noPay') {
							//直接租赁成功  跳转至门店订单页
							// _this.$refer.setVilit('/pages/pay/success/success')
							let url= _this.$refer.setVilit('/packageUser/pages/user/pay/pay-success');
							let callback = function(url) {
								_this.$refs.popupvLogin.open()
							}
							var data = {
								amount: _this.payment,
								product_name:_this.data.list.name
							}

							_this.$refer.toUrl(callback, data, 'reLaunch')

							return
						}else if(res.status != 1){
							let options = {
								msg: res.message,
								type: 'danger'
							};
							
							_this.$refs.toast.showTips(options);
							
						}else {

							let options = {
								msg: res.message,
								type: 'danger'
							};
							if(res.status != 1){
								_this.$refs.toast.showTips(options);
							}

						}
						



					}
				};

				this.$service.GetApi(opt)
				// #endif
			},
			connectSocketInit() {
				const _this = this
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url:this.$service.getWssHost(),
					success(data) {
						console.log("websocket连接成功");
						//发送心跳包
						_this.startHeart()
					},
				});

				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					this.checkCashStatus()
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
			},
			//检测免押订单状态
			checkCashStatus() {
				var _this = this
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】

					let sendData = JSON.stringify({
						user_id: store.getters.userId,
						order_no: store.getters.orderNo
					})
					console.log(sendData)
					// let sendData = JSON.stringify({
					// 	user_id:36657,
					// 	order_no:'C2021033114542160641c9d3f061'
					// })
					sendData = this.$service.encryptDesIv(sendData)

					this.socketTask.send({
						data: sendData,
						async success() {
							console.log("消息发送成功");
						},
					});

					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						// console.log("收到服务器内容：" + JSON.stringify(res));
						//console.log(res.data);
						let rvcs = JSON.parse(res.data)
						if (rvcs.status == 1) {
							// 检测到免押订单已支付   关闭支付加载
							_this.showMaskloading = false;
							_this.selectCashCode = 'onlinePay'
							_this.data.usable_cash.status = true;
							_this.data.usable_cash.cash_code = 'wechatFreePay';
							let options = {
								msg: rvcs.msg,
								type: 'green'
							};
							_this.$refs.toast.showTips(options);
							//关闭心跳包
							clearInterval(this.timeoutObj)
							this.timeoutObj = ''


						} else {
							//心跳包存在才往服务器继续推送订单信息

							if (this.timeoutObj != '') {
								setTimeout((res) => { //未找到支付订单，继续推送信息
									let sendData = JSON.stringify({
										user_id:store.getters.userId,
										order_no: store.getters.orderNo
									})
									// let sendData = JSON.stringify({
									// 	user_id:36657,
									// 	order_no:'C2021033114542160641c9d3f061'
									// })
									sendData = this.$service.encryptDesIv(sendData)
									this.socketTask.send({
										data: sendData,
										async success() {
											console.log("消息发送成功");
										},
									});
								}, 3500);

							}
						}
					});

				}

			},
			startHeart() {
				if (this.timeoutObj == '') {
					this.timeoutObj = setInterval(function() {

						uni.sendSocketMessage({
							data: 'ping',
							success: res => {
								console.log('连接中....');
							},
							fail: err => {
								console.log('连接失败重新连接....');
								console.log(err)
								// this.openConnection();
							}
						});
					}, 3000);

				}
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
						//关闭心跳包
						clearInterval(this.timeoutObj)
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			//配送类型
			radioChange: function(evt) {
				//console.log(this.data.nearbyStore)
				//console.log(parseInt(evt.target.value))
				this.deliver_type = parseInt(evt.target.value)
				//线条BUG控制。我也不懂什么原因。MMP
				this.pageStyle = parseInt(evt.target.value) > 0 ? 0 : 1
			},
			seleteDeliverStore() {
				this.$refs.deliverStore.show();
			},
			onConfirm(e) {

				this.deliverStoreObj.text = e.label
				this.deliverStoreObj.key = e.index[0]
				this.deliverStoreObj.val = e.value[0]

			}

		}
	}
</script>

<style lang="scss">
	@import "./submit_order.scss";

	page {}
</style>

